import jwt from 'jsonwebtoken'
import { NextRequest } from 'next/server'

const JWT_SECRET = process.env.JWT_SECRET || 'fallback-secret-do-not-use-in-production'
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'

export interface JwtPayload {
  userId: string
  email: string
  name: string
}

// 生成JWT令牌
export function signJwtToken(payload: JwtPayload): string {
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: JWT_EXPIRES_IN
  })
}

// 验证JWT令牌
export function verifyJwtToken(token: string): JwtPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as JwtPayload
  } catch (error) {
    console.error('JWT验证失败:', error)
    return null
  }
}

// 从请求中获取JWT令牌
export function getJwtTokenFromRequest(req: NextRequest): string | null {
  const authHeader = req.headers.get('authorization')
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null
  }
  
  return authHeader.split(' ')[1]
}

// 从请求中获取用户信息
export function getUserFromRequest(req: NextRequest): JwtPayload | null {
  const token = getJwtTokenFromRequest(req)
  if (!token) return null
  
  return verifyJwtToken(token)
} 